<?php

/**
 * Louder Cache
 *
 * LICENSE
 *
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file docs/LICENSE.txt.
 *
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to info@loudertechnology.com so we can send you a copy immediately.
 *
 * @category Louder
 * @package ConfigReader
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */

/**
 * Lectura de archivos de configuracion XML
 *
 * @category Louder
 * @package ConfigReader
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */
class ConfigReader {

	/**
	 * Archivos de configuracion leidos
	 *
	 * @var array
	 */
	private static $_readedFiles = array();

	/**
	 * Documento XML del Objeto
	 *
	 * @var DOMDocument
	 */
	private $_xmlDocument;

	/**
	 * Constructor de ConfigReader
	 *
	 * @param string $configFile
	 */
	public function __construct($configFile){
		$configFile = (string) $configFile;
		if(isset(self::$_readedFiles[$configFile])==false){
			if(file_exists($configFile)==false){
				throw new ConfigReaderException("No existe el archivo de configuración config-server.xml");
			}
			$fileContent = file_get_contents($configFile);
			$xmlDocument = new DOMDocument();
			if($xmlDocument->loadXML($fileContent)==false){
				throw new ConfigReaderException("El archivo de configuración '$configFile' es invalido");
			} else {
				self::$_readedFiles[$configFile] = $xmlDocument;
				$this->_xmlDocument = $xmlDocument;
			}
		} else {
			$this->_xmlDocument = self::$_readedFiles[$configFile];
		}
	}

	/**
	 * Obtiene el valor de un atributo de un nodo
	 *
	 * @param string $nodeName
	 * @param string $attributeName
	 * @return string
	 */
	public function getAttributeFromNode($nodeName, $attributeName){
		$nodeList = $this->_xmlDocument->getElementsByTagName($nodeName);
		foreach($nodeList as $node){
			return $node->getAttribute($attributeName);
		}
	}

	/**
	 * Devuelve los atributos y sus valores de un nodo en forma de un array
	 *
	 * @param string $nodeName
	 * @return array
	 */
	public function getAttributesFromNode($nodeName){
		$nodeList = $this->_xmlDocument->getElementsByTagName($nodeName);
		foreach($nodeList as $node){
			$attributes = array();
			foreach($node->attributes as $attribute){
				$attributes[$attribute->nodeName] = $attribute->nodeValue;
			}
			return $attributes;
		}

	}

}